import { ref } from "vue"
import { CountDownOption } from "../../../../types/tn-count-down"
import { subNumber } from '../../../../utils'

/**
 * 处理倒计时的时间
 */
type CountDownInfo = {
  time: number,
  day: string,
  hour: string,
  minute: string,
  second: string
}
const SECOND = 1
const MINUTE = 60 * SECOND
const HOUR = 60 * MINUTE
const DAY = 24 * HOUR
export default function useCountDownTime(endFn?: Function) {

  // 倒计时配置信息
  let option: CountDownOption = {}
  // 倒计时的时间
  let time: number = 0
  // 倒计时定时器
  let countDownTimer: number | null = null
  // 倒计时时间分段信息
  let countDownInfo = ref<CountDownInfo>({
    time: 0,
    day: '',
    hour: '',
    minute: '',
    second: ''
  })

  // 更新时间
  const updateTime = (_time: number, autoplay: boolean = false) => {
    time = _time
    if (autoplay) startCountDown()
  }
  // 更新配置
  const updateOption = (_option: CountDownOption) => {
    option = _option
  }

  // 开始执行倒计时
  const startCountDown = () => {
    // 开始前先清空一下
    stopCountDown()
    countDownTimer = setInterval(() => {
      // 如果为0则已经倒计结束了
      if (time <= 0) {
        endFn && endFn()
        stopCountDown()
        return
      }
      _formatTime()
      time--
    }, 1000)
  }

  // 停止/清空倒计时
  const stopCountDown = () => {
    if (countDownTimer !== null) {
      clearInterval(countDownTimer)
      countDownTimer = null
    }
  }

  // 格式化时间
  const _formatTime = () => {
    let [day, hour, minute, second]: (string|number)[] = [0, 0, 0, 0]
    day = option.day ? Math.floor(time / DAY) : ''
    // 如果不显示天将时间加到小时中
    hour = option.hour ? (option.day ? Math.floor((time % DAY) / HOUR) : Math.floor(time / HOUR)) : ''
    minute = option.minute ? Math.floor((time % HOUR) / MINUTE) : ''
    second = option.second ? Math.floor(time % MINUTE): ''

    // 如果是自动隐藏天数，当天数为0时则取空
    if (option.autoHiddenDay && day === 0) day = ''

    countDownInfo.value.day = subNumber(day, 4)
    countDownInfo.value.hour = subNumber(hour, 4)
    countDownInfo.value.minute = subNumber(minute)
    countDownInfo.value.second = subNumber(second)
    countDownInfo.value.time = time
  }

  return {
    countDownInfo,
    updateOption,
    updateTime,
    startCountDown,
    stopCountDown
  }
}